import React, { PureComponent } from 'react'
import { Row, Col, Input, Button, Icon, Select, DatePicker, InputNumber } from 'antd'
import moment from 'moment'
import * as R from 'ramda'
import store from '../../index'
import { transferOption, isNotEmptyAndNil } from '@/utils/common'
import styles from './index.less'
import { Form } from '@ant-design/compatible';

const { dispatch } = store
const { RangePicker } = DatePicker
const FormItem = Form.Item
const InputGroup = Input.Group;
const dateFormat = 'YYYY-MM-DD HH:mm:ss'

@Form.create()
export default class CustomerSearchForm extends PureComponent {

  state = {
  };
  getFieldsValue = () => {
    const { form: { validateFields }, dateFormatList, dateFormatListNoTime, handleRangePicker } = this.props
    // console.log(getFieldsValue());
    // return getFieldsValue();
    return new Promise((resolve) => {
      validateFields((err, fieldsValue) => {
        if (err) {
          resolve(false);
          return
        }
  
        for (let para in fieldsValue) {
          if (!fieldsValue[para] || !fieldsValue[para].toString().trim()) {
            fieldsValue[para] = undefined
          }
        }
  
        if (handleRangePicker) {
          const rangePicker = handleRangePicker(fieldsValue)
          if (isNotEmptyAndNil(rangePicker)) {
            resolve(false);
            return;
          }
        }
  
        // dateFormatList:是用来格式化时间的
        if (dateFormatList) {
          dateFormatList.map(title => fieldsValue[title] ?
            (fieldsValue[title] = moment(fieldsValue[title]).format('YYYY-MM-DD HH:mm:ss')) : (fieldsValue[title] = undefined))
        }
  
        // dateFormatListNoTime:是用来格式化日期的
        if (dateFormatListNoTime) {
          dateFormatListNoTime.map(title => fieldsValue[title] ?
            (fieldsValue[title] = moment(fieldsValue[title]).format('YYYY-MM-DD')) : (fieldsValue[title] = undefined))
        }
        resolve(fieldsValue);
      })
    })
  }
  handleSearch = e => {
    e.preventDefault()
    const { form: { validateFields }, fetchUrl, payloadUrl, saveFormValues, dateFormatList, dateFormatListNoTime, handleRangePicker } = this.props
    validateFields((err, fieldsValue) => {
      if (err) return

      for (let para in fieldsValue) {
        if (!fieldsValue[para] || !fieldsValue[para].toString().trim()) {
          fieldsValue[para] = undefined
        }
      }

      if (handleRangePicker) {
        const rangePicker = handleRangePicker(fieldsValue)
        if (isNotEmptyAndNil(rangePicker)) return
      }

      // dateFormatList:是用来格式化时间的
      if (dateFormatList) {
        dateFormatList.map(title => fieldsValue[title] ?
          (fieldsValue[title] = moment(fieldsValue[title]).format('YYYY-MM-DD HH:mm:ss')) : (fieldsValue[title] = undefined))
      }

      // dateFormatListNoTime:是用来格式化日期的
      if (dateFormatListNoTime) {
        dateFormatListNoTime.map(title => fieldsValue[title] ?
          (fieldsValue[title] = moment(fieldsValue[title]).format('YYYY-MM-DD')) : (fieldsValue[title] = undefined))
      }

      // saveFormValues:子组件向父组件传递表单的数据 和 dateFormatList 的顺序不可颠倒。
      if (saveFormValues) saveFormValues(fieldsValue)
      if (this.props.customHandleSearch) {
        this.props.customHandleSearch(fieldsValue);
        return;
      }
      dispatch({
        type: fetchUrl,
        payload: payloadUrl ? Object.assign(payloadUrl, fieldsValue) : fieldsValue,
      })
    })
  }
  componentDidMount () {
    this.props.onRef && this.props.onRef(this);
  }
  handleFormReset = () => {
    const { form, fetchUrl, payloadUrl, handleFormReset, customHandleFormReset } = this.props
    form.resetFields()
    if (customHandleFormReset) {
      customHandleFormReset()
      return
    }
    if (handleFormReset) { handleFormReset() }
    dispatch({
      type: fetchUrl,
      payload: payloadUrl || {},
    })
  }

  renderForm = () => {
    const { form: { getFieldDecorator }, searchItems = [] } = this.props
    const loopFormItems = data => data.map((item, i) => {
      const { title, key, type, max = Infinity } = item
      switch (type) {
        case 'input': {
          const placeholder = `请输入${typeof (title) === 'string' ? title : ''}`
          return (
            <Col md={8} sm={24} key={key}>
              <FormItem
                key={key}
                label={title}
              >
                {getFieldDecorator(key)(
                  <Input placeholder={placeholder} autoComplete='off' allowClear maxLength={max} />
                )}
              </FormItem>
            </Col>
          )
        }
        case 'inputNumber': {
          const { min, max, precision, holder } = item
          const placeholder = `请输入${typeof (title) === 'string' ? title : ''}`
          return (
            <Col md={8} sm={24} key={key}>
              <FormItem
                key={key}
                label={title}
              >
                {getFieldDecorator(key)(
                  <InputNumber placeholder={holder ? holder : placeholder} min={min} max={max} precision={precision} style={{ width: '100%' }} />
                )}
              </FormItem>
            </Col>
          )
        }
        case 'select': {
          const { selectOptions, keyValue, onSelectChange, initialValue, cantClear, mode, placeholder, optionLabelProp, onSearch, onSelect } = item
          const options = { initialValue }
          return (
            <Col md={8} sm={24} key={key}>
              <FormItem key={key} label={title}>
                {getFieldDecorator(key, { ...options })(
                  <Select
                    placeholder={placeholder ? placeholder : '请选择'}
                    showSearch
                    optionFilterProp="children"
                    allowClear={!cantClear}
                    onChange={onSelectChange}
                    //getPopupContainer={triggerNode => triggerNode.parentNode}
                    getPopupContainer={() => document.getElementById("public")}
                    mode={mode}
                    optionLabelProp={optionLabelProp}
                    onSearch={onSearch}
                    onSelect={onSelect}
                    style={{width: '100%'}}
                  >
                    {transferOption(selectOptions, keyValue)}
                  </Select>
                )}
              </FormItem>
            </Col>
          )
        }
        case 'datePicker': {
          const { nohmsFormat, noTimeSelect } = item
          return (
            <Col md={8} sm={24} key={key}>
              <FormItem key={key} label={title}>
                {getFieldDecorator(key)(
                  <DatePicker
                    showTime={!noTimeSelect}
                    format={nohmsFormat ? nohmsFormat : dateFormat}
                    showToday
                    getCalendarContainer={trigger => trigger.parentNode}
                  />
                )}
              </FormItem>
            </Col>
          )
        }
        case 'rangePicker': {
          // 这里不再推荐使用noTimeSelect,showTime,
          const { nohmsFormat, noTimeSelect, specialStyle, disabledDate, disabledTime, showTime, style, dateRender } = item
          return (
            <Col md={specialStyle || 8} sm={24} key={key}>
              <FormItem key={key} label={title}>
                {getFieldDecorator(key)(
                  <RangePicker
                    style={style}
                    disabledDate={disabledDate}
                    disabledTime={disabledTime}
                    showTime={R.isNil(showTime) ? !noTimeSelect : showTime}
                    format={nohmsFormat ? nohmsFormat : dateFormat}
                    placeholder={['开始时间', '结束时间']}
                    ranges={{
                      '本周 ': [moment().startOf('weeks'), moment()],
                      '最近一周 ': [moment().add(-1, 'weeks'), moment()],
                      '本月 ': [moment().startOf('months'), moment()],
                      '最近一个月 ': [moment().add(-1, 'months'), moment()],
                    }}
                    dateRender={dateRender}
                    getCalendarContainer={trigger => trigger.parentNode}
                  />
                )}
              </FormItem>
            </Col>
          )
        }
      }
    })
    return loopFormItems(searchItems)
  }
  // 逾期天数计算符：大于、小于、介于
  overdueFlagChanged = (value) => {
    const { form: { setFieldsValue, getFieldValue } } = this.props
    const overdueFlag = getFieldValue("overdueFlag")
    const overdueDay = getFieldValue("overdueDay")
    console.log(value, overdueFlag)

    // setFieldsValue({ dealerId: [] })
  };
  render () {
    const { form: { getFieldDecorator, getFieldValue } } = this.props
    const overdueFlag = getFieldValue("overdueFlag")
    return (
      <div className={styles.tableListForm} id={"public"}>
        <Form onSubmit={this.handleSearch} layout='inline'>
          <Row gutter={24}>
            {this.renderForm()}
            <Col md={8} sm={24} key='overdueDaysGroup'>
              <FormItem label='逾期天数'>
              <InputGroup compact>
                <div className={styles.inputDiv}>
                  <FormItem
                    key='overdueFlag'
                    name='overdueFlag'
                  >
                    {getFieldDecorator('overdueFlag')(
                      <Select placeholder="请选择"  onChange={this.overdueFlagChanged} allowClear>
                        <Select.Option value="大于">大于</Select.Option>
                        <Select.Option value="小于">小于</Select.Option>
                        <Select.Option value="介于">介于</Select.Option>
                      </Select>
                    )}
                  </FormItem>
                  </div>
                  <div className={styles.inputDiv}> 
                  <FormItem
                    key='overdueDay'
                    name='overdueDay'
                    style={{flex: 1 }}

                  >
                    {getFieldDecorator('overdueDay', {
                      rules: [{ required: !!overdueFlag, message: '请填写天数' }]
                    })(
                      <InputNumber  placeholder="请填写天数" min={0} allowClear />
                    )}
                  </FormItem>
                  </div>
                  <div className={styles.inputDiv}>
                  {overdueFlag === '介于' && <FormItem
                    key='overdueDayEnd'
                    name='overdueDayEnd'
                    style={{flex: 1 }}
                  >
                    {getFieldDecorator('overdueDayEnd', {
                      rules: [{ required: true, message: '请填写天数' }]
                    })(
                      <InputNumber  placeholder="请填写天数" min={0} allowClear />
                    )}
                  </FormItem>}
                  </div>
                </InputGroup>
              </FormItem>
            </Col>
           </Row>
           <Row>
            <Col span={8} offset={16}>
              <span style={{float: 'right'}}>
                {this.props.moreFn ?  <Button
                      style={{ marginRight: "10px" }}
                      onClick={() => {
                        const { form: { validateFields }, fetchUrl, payloadUrl, saveFormValues, dateFormatList, dateFormatListNoTime, handleRangePicker } = this.props
                        validateFields((err, fieldsValue) => {
                          if (err) return
                    
                          for (let para in fieldsValue) {
                            if (!fieldsValue[para] || !fieldsValue[para].toString().trim()) {
                              fieldsValue[para] = undefined
                            }
                          }
                    
                          if (handleRangePicker) {
                            const rangePicker = handleRangePicker(fieldsValue)
                            if (isNotEmptyAndNil(rangePicker)) return
                          }
                    
                          // dateFormatList:是用来格式化时间的
                          if (dateFormatList) {
                            dateFormatList.map(title => fieldsValue[title] ?
                              (fieldsValue[title] = moment(fieldsValue[title]).format('YYYY-MM-DD HH:mm:ss')) : (fieldsValue[title] = undefined))
                          }
                    
                          // dateFormatListNoTime:是用来格式化日期的
                          if (dateFormatListNoTime) {
                            dateFormatListNoTime.map(title => fieldsValue[title] ?
                              (fieldsValue[title] = moment(fieldsValue[title]).format('YYYY-MM-DD')) : (fieldsValue[title] = undefined))
                          }
                    
                          // saveFormValues:子组件向父组件传递表单的数据 和 dateFormatList 的顺序不可颠倒。
                          if (saveFormValues) saveFormValues(fieldsValue)
                          if (this.props.customHandleSearch) {
                            this.props.moreFn(fieldsValue);
                            return;
                          }
                        })
                      }}
                    >更多筛选条件</Button> : ''}
                <Button type='primary' htmlType='submit'>查询</Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
              </span>
            </Col>
          </Row>
        </Form>
      </div>
    )
  }
}

